﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Catering.Catering_Page.Caipin.Caipin_jcsz.Entity;
using Catering_DBOpertion;
using Catering_Rules;
using Catering_Model;
using NopiCommon;


namespace Catering.Catering_Page.Caipin.Caipin_jcsz
{
    public partial class shipu_clone05 : UserIsNull
    {
        T_Recipes tRecipes = new T_Recipes();//食谱管理
        Catering_Rules.T_RecipesWeek tRecipesWeek = new T_RecipesWeek();//食谱周期管理
        Catering_Rules.T_RecipeInformation tRecipeInformation = new T_RecipeInformation();//食谱菜品管理
        Catering_Rules.T_RecipeInformationInfo tRecipeInformationInfo = new T_RecipeInformationInfo();//食谱菜品用量详细管理
        Catering_Rules.ClassInfo tClassInfo = new Catering_Rules.ClassInfo();//班组管理

        public string pc_person = "";   //配餐人群 
        public string pc_zhouqi = "";   //配餐周期
        public string pc_class = "";    //所属班组 
        public string pc_number = "";   //人数 
        public int m_weekno = 0;   //周selecteNO
        public int m_recipesid = 0;     //食谱ID
        public int m_dishid = 0;     //菜谱ID
        public int m_daybyweek = 7;     //每周天数，默认为7天
        public string m_weekstart = ""; //每周开始时间
        public string m_weekend = "";   //每周结束时间
        public string m_shiwuzhongsh = "";//食物种属
        public int m_canedit = 0;//是否可编辑（0：不可编辑，1：可编辑）
        public string m_DishTypesList = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            m_recipesid = GetInt("cid", 0);
            m_weekno = GetInt("weekno", 0);
            m_dishid = GetInt("dishid", ConfigHelper.GetConfigInt("LibraryID"));
            if (!IsPostBack)
            {
                LoadRep();//加载食谱库
                LoadRecipesInfo();//加载相关食谱信息
                this.LoadCopyRecipesList();//加载可复制食谱列表
                m_shiwuzhongsh = GetShiWuZhongShu();

                if (Request.QueryString["RecipesId"] != null)
                {
                    this.hf_weekNo.Value = "0";//默认为第一周
                    this.hf_recipesid.Value = Request.QueryString["RecipesId"].ToString();
                    this.Recipes_List_Click(null, null);
                }
            }
        }

        /// <summary>
        /// 加载相关食谱信息
        /// </summary>
        private void LoadRecipesInfo()
        {
            if (m_recipesid > 0)
            {
                //绑定周期pc_week
                DataTable dt_Week = new Catering_Rules.T_RecipesWeek().GetList(100, "RecipesID=" + m_recipesid.ToString(), "Number").Tables[0];
                if (dt_Week != null && dt_Week.Rows.Count > 0)
                {
                    this.pc_week.LoadDrop(dt_Week, "id", "temp1");//周
                    this.pc_week.SelectedIndex = m_weekno;
                }

                Catering_Model.E_Recipes md = new Catering_Rules.T_Recipes().GetModel(m_recipesid);
                if (md != null)
                {
                    pc_person = md.CateringName;//配餐人群
                    pc_number = md.Number.ToString() == "0" ? "1" : md.Number.ToString();//人数 
                    pc_class = new Catering_Rules.ClassInfo().GetModel(md.ClassID).CName;//所属班组
                    if (Base_Classid == md.ClassID) m_canedit = 1;
                    Catering_Model.E_RecipesWeek md_Week = new Catering_Rules.T_RecipesWeek().GetModel(Convert.ToInt32(this.pc_week.SelectedValue));
                    if (md_Week != null)
                    {
                        m_weekstart = md_Week.startDate.ToString("yyyy-MM-dd");//每周开始时间
                        m_weekend = md_Week.endDate.ToString("yyyy-MM-dd");//每周结束时间
                        pc_zhouqi = m_weekstart + "至" + m_weekend; //配餐周期
                        m_daybyweek = (md_Week.endDate - md_Week.startDate).Days + 1;//每周天数
                    }
                }
                m_DishTypesList = InitDishTypes();
            }
        }

        //加载可复制食谱列表
        private void LoadCopyRecipesList()
        {
            DataTable dt_RecipesByIsBiaoZhun = new DataTable();
            DataTable dt_RecipesByClass = new DataTable();

            dt_RecipesByIsBiaoZhun = new Catering_Rules.T_Recipes().GetList(
                    " (ClassID IN(SELECT ClassID FROM View_CompanyClass WHERE "
                    + " CompanyID=(SELECT TOP 1 CompanyID FROM View_CompanyClass WHERE ClassID="
                    + LoginPersonnel.ClassID + ")) AND IsBiaoZhun=1 )").Tables[0];
            if (LoginPersonnel.RoleName == "管理员")
            {
                dt_RecipesByClass = tRecipes.GetList("").Tables[0];//获取本区域内的食谱 区域测试屏蔽 "AID=" +  LoginPersonnel.AreaID
            }
            else
            {
                if (LoginPersonnel.ClassID > 0)
                {
                    dt_RecipesByClass = new Catering_Rules.T_Recipes().GetList(" ClassID=" + LoginPersonnel.ClassID).Tables[0];
                }
            }
            this.Rep_CopyRecipesList.DataSource = dt_RecipesByIsBiaoZhun;
            this.Rep_CopyRecipesList.DataBind();

            this.Rep_CopyRecipesListByClass.DataSource = dt_RecipesByClass;
            this.Rep_CopyRecipesListByClass.DataBind();
        }

        private string GetShiWuZhongShu()
        {
            StringBuilder result = new StringBuilder("");
            //<dd class="shiwu_left_span">食物种属</dd><dt rawtype="shiwu_0" rawtypevalue='0'>0克</dt>
            DataTable dt = new Catering_Rules.RawMaterialsType().GetAllList().Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string id = dt.Rows[i]["id"].ToString();
                    string Name = dt.Rows[i]["Name"].ToString();
                    result.Append("<dl><dd>" + Name + "</dd><dt rawtype='shiwu_" + id + "' rawtypevalue='0'>0g</dt></dl>");
                }
                dt.Dispose();
            }
            return result.ToString();
        }

        public string InitDishTypes()
        {
            StringBuilder result = new StringBuilder("");
            DataTable dt = new Catering_Rules.DishType().GetAllList().Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                Dictionary<int, string> dic = new Catering_Rules.RecipesRuleManage().GetRuleTypelist();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int id = Convert.ToInt16(dt.Rows[i]["id"]);
                    string dtname = dt.Rows[i]["DT"].ToString();
                    result.Append("<div class='tp_ui'>");
                    result.Append("<span class='tp_t'> " + dtname + "　》</span>");
                    result.Append("<dl class='dps_ui'>");
                    DataTable dt_info = new Catering_Rules.DishTypes().GetList(" DTID=" + id).Tables[0];
                    if (dt_info != null && dt_info.Rows.Count > 0)
                    {
                        for (int k = 0; k < dt_info.Rows.Count; k++)
                        {
                            int dtsid = Convert.ToInt16(dt_info.Rows[k]["id"]);
                            string dtsname = dt_info.Rows[k]["DTName"].ToString();
                            int df_rule = 1;
                            int df_no = 0;
                            Catering_Model.RecipesRule rr = new Catering_Rules.RecipesRule().GetModel(m_recipesid, dtsid);
                            if (rr != null)
                            {
                                df_rule = rr.Repeatype;
                                df_no = rr.RepeatNo;
                            }
                            else
                            {
                                Catering_Model.RecipesRuleManage rm = new Catering_Rules.RecipesRuleManage().GetModel(dtsid);
                                df_rule = rm.Repeatype;
                                df_no = rm.DefaultNo;
                            }
                            string options = GetOptions(dic, df_rule);
                            result.Append("<dd><span>" + dtsname + "：</span><select disabled='disabled' typesid='" + dtsid + "'>" + options + "</select><input type='text' ntypesid='" + dtsid + "' value='" + df_no + "' style='width:20px;' /></dd>");
                        }
                        dt_info.Dispose();
                    }
                    result.Append("</dl>");
                    result.Append("<div class='clear'></div>");
                    result.Append("</div>");
                }
                dt.Dispose();
            }
            return result.ToString();
        }

        /// <summary>
        /// 获取标准列表信息
        /// </summary>
        /// <returns></returns>
        public string GetOptions(Dictionary<int, string> dic, int selectvalue)
        {
            StringBuilder result = new StringBuilder("");

            foreach (int key in dic.Keys)
            {
                if (key == selectvalue)
                    result.Append("<option value='" + key + "' selected='selected'>" + dic[key] + "</option>");
                else
                    result.Append("<option value='" + key + "'>" + dic[key] + "</option>");
            }
            return result.ToString();
        }

        [WebMethod]
        public static string GetRecipesRule(string recipes)
        {
            StringBuilder result = new StringBuilder("");
            int id = 0;
            Int32.TryParse(recipes, out id);
            if (id <= 0) return "";
            DataTable dt = new Catering_Rules.RecipesRule().GetList(" RecipesID=" + recipes).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                result.Append("{\"RuleInfo\":[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int no = Convert.ToInt32(dt.Rows[i]["RepeatNo"]);
                    int typeid = Convert.ToInt32(dt.Rows[i]["DTID"]);
                    int repeattype = Convert.ToInt32(dt.Rows[i]["Repeatype"]);
                    result.Append("{\"DTID\":\"" + typeid + "\",\"No\":\"" + no + "\",\"RepeatType\":\"" + repeattype + "\"}");
                    if (i < dt.Rows.Count - 1)
                    {
                        result.Append(",");
                    }
                }
                dt.Dispose();
                result.Append("]}");
            }
            return result.ToString();
        }

        //显示日菜品
        [WebMethod]
        public static string GetDishRawMater(string StrRecipeID, string StrWeekNoID, string StrDateNo)
        {
            int t_recipeid = 0;//recipes表ID
            int t_recipesweek = 0;//RecipesWeek表ID
            int t_dateno = 0;//第几天(0为周日)
            Int32.TryParse(StrRecipeID, out t_recipeid);
            Int32.TryParse(StrWeekNoID, out t_recipesweek);
            Int32.TryParse(StrDateNo, out t_dateno);
            string where = string.Format(" [RecipesID]={0} AND [RecipesWeekID]={1} AND [dayofweek]={2} ", t_recipeid, t_recipesweek, t_dateno);
            DataTable dt = new Catering_Rules.T_RecipeInformation().GetViewList(where);
            //Catering_Model.Recipes md = new Catering_Rules.Recipes().GetModel(t_recipeid);
            //string jison = new JavaScriptSerializer().Serialize(md);
            return GetJsonFromViewRecipes(dt);
        }

        //加载菜谱详细
        [WebMethod]
        public static ArrayList GetDishInfoByLish(string Lid, string StrRecipesID, string StrIndex, string StrSize, string StrDishNum)
        {
            ArrayList al = new ArrayList();
            StringBuilder sb = new StringBuilder();
            DataTable dt_DishType = new Catering_Rules.DishType().GetAllList(false).Tables[0];    //菜品分类
            DataTable dt_library_Dish = new Catering_Rules.library_Dish().GetList("libraryID=" + Lid).Tables[0]; //菜谱列表
            int AreaID = ((E_Personnel)HttpContext.Current.Session["UserInfo"]).AreaID;
            DataTable dt_Dish = new Catering_Rules.T_Dish().GetList("").Tables[0];   //菜品列表  区域测试屏蔽 AreaIDS like '%," + AreaID + ",%'
            Catering_Model.library md_l = new Catering_Rules.library().GetModel(Convert.ToInt32(Lid)); //当前菜谱

            int t_recipeid = 0;//recipes表ID
            int dishnum = 0;
            Int32.TryParse(StrRecipesID, out t_recipeid);
            Catering_Model.E_Recipes md_r = new Catering_Rules.T_Recipes().GetModel(t_recipeid);    //食谱表
            //检查原料的配送区域
            Catering_Model.ClassInfo md_class = new Catering_Rules.ClassInfo().GetModel(md_r.ClassID); //班组详细表
            if (md_class.id != 50 && md_class.AID <= 0)
            {
                al.Add("");
                al.Add(0);
                al.Add("");
                al.Add(0);
                al.Add(0);
                return al;
            }
            int type_index = 0;
            int max_type_index = 0;
            int start_index = 0;
            Int32.TryParse(StrIndex, out type_index);
            Int32.TryParse(StrSize, out max_type_index);

            string TypeTemp = "<li><a iscai='false' typeid='{$id}' isload='false'>{$DT}</a>#content#</li>";
            string DishTemp = "<li><a iscai='true' uid='{$id}'>{$Name}</a></li>";
            DataRow[] TypeList = dt_DishType.Select("ParentID=0");
            string DishHtml = AddDishHtml(TypeList, TypeTemp, DishTemp, dt_DishType, dt_Dish, dt_library_Dish, md_class, ref dishnum);
            sb.Append(DishHtml);
            al.Add(sb.ToString());
            al.Add(dishnum);
            al.Add(md_l.LName);
            al.Add((start_index));
            al.Add(1);
            return al;
        }

        /// <summary>
        /// 获取菜品树形菜单
        /// </summary>
        /// <param name="TypeList">类别集合</param>
        /// <param name="TypeTemp">类别循环模板</param>
        /// <param name="DishTemp">菜品循环模板</param>
        /// <returns>返回菜品树形菜单</returns>
        private static string AddDishHtml(DataRow[] TypeList, string TypeTemp, string DishTemp, DataTable dt_DishType, DataTable dt_Dish, DataTable dt_library_Dish, Catering_Model.ClassInfo md_class, ref int dishnum)
        {
            StringBuilder TypeHtml = new StringBuilder();
            foreach (DataRow row in TypeList)
            {
                string Temp = GetLoopContent(row, TypeTemp);
                DataRow[] child = dt_DishType.Select("ParentID=" + row["id"].ToString());
                string TempTypeHtml = AddDishHtml(child, TypeTemp, DishTemp, dt_DishType, dt_Dish, dt_library_Dish, md_class, ref dishnum);
                int DishCount = GetDishCountByTypeID(row["id"].ToString(), DishTemp, dt_Dish, dt_library_Dish, md_class);
                dishnum += DishCount;
                string Tempcontents = string.Format("<ul class='treeview display_none'>{0}{1}</ul>", TempTypeHtml, "");
                TypeHtml.Append(Temp.Replace("#content#", Tempcontents));
            }
            return TypeHtml.ToString();
        }

        /// <summary>
        /// 获取符合要求的菜品数量
        /// </summary>
        /// <returns></returns>
        private static int GetDishCountByTypeID(string DTID, string DishTemp, DataTable dt_Dish, DataTable dt_library_Dish, Catering_Model.ClassInfo md_class)
        {
            int DishCount = 0;
            DataRow[] DishList = dt_Dish.Select("DTID=" + DTID);
            for (int i = 0; i < DishList.Length; i++)
            {
                if (dt_library_Dish.Select("DishID=" + DishList[i]["id"].ToString()).Count() > 0)
                {
                    DataRow row = DishList[i];
                    bool flag = true;
                    DataTable dt_info = new Catering_Rules.T_DishInfo().GetList(" DID=" + row["id"].ToString() + " ").Tables[0];
                    //验证配送区域
                    if (md_class.id != 50 && dt_info != null)
                    {
                        foreach (DataRow item0 in dt_info.Rows)
                        {
                            string RawID = item0["RawID"].ToString();
                            string checkwhere = " RAWID=" + RawID + " AND InDBID LIKE '" + md_class.AID + "%'";
                            DataTable dt_ck = new Catering_Rules.RawMaterial_Area().GetList(checkwhere).Tables[0];
                            if (dt_ck.Rows.Count == 0)
                            {
                                flag = false;
                                break;
                            }
                        }
                        dt_info.Dispose();
                    }
                    if (flag)
                    {
                        DishCount += 1;
                    }
                }
            }
            return DishCount;
        }



        [WebMethod]
        public static ArrayList GetDishListByTypeID(string Lid, string StrRecipesID, string DishTypeID)
        {
            ArrayList al = new ArrayList();
            int t_recipeid = 0;//recipes表ID
            Int32.TryParse(StrRecipesID, out t_recipeid);
            Catering_Model.E_Recipes md_r = new Catering_Rules.T_Recipes().GetModel(t_recipeid);    //食谱表
            Catering_Model.ClassInfo md_class = new Catering_Rules.ClassInfo().GetModel(md_r.ClassID); //班组详细表
            int AreaID=((E_Personnel)HttpContext.Current.Session["UserInfo"]).AreaID;
            DataTable dt_Dish = new Catering_Rules.T_Dish().GetList("").Tables[0];   //菜品列表 区域测试屏蔽  AreaIDS like '%," + AreaID + ",%'
            DataTable dt_DishType = new Catering_Rules.DishType().GetAllList(false).Tables[0];    //菜品分类
            DataTable dt_library_Dish = new Catering_Rules.library_Dish().GetList("libraryID=" + Lid).Tables[0]; //菜谱列表
            string DishTemp = "<li><a iscai='true' uid='{$id}'>{$Name}</a></li>";
            List<E_DishInfoEntity> EDishList = new List<E_DishInfoEntity>();
            GetDishHtml(DishTypeID, DishTemp, dt_Dish, dt_library_Dish, md_class, EDishList);
            string DishHtml = JsonHelper.Serialize<List<E_DishInfoEntity>>(EDishList);
            al.Add("OK");
            al.Add(DishHtml);
            return al;
        }

        /// <summary>
        /// 根据类别ID 获取对应的菜品Html集合
        /// </summary>
        /// <param name="DTID">菜品类别ID</param>
        /// <returns>返回所有菜品的Html</returns>
        private static string GetDishHtml(string DTID, string DishTemp, DataTable dt_Dish, DataTable dt_library_Dish, Catering_Model.ClassInfo md_class, List<E_DishInfoEntity> EDishList)
        {
            StringBuilder DishHtml = new StringBuilder();
            DataRow[] DishList = dt_Dish.Select("DTID=" + DTID);
            for (int i = 0; i < DishList.Length; i++)
            {
                if (dt_library_Dish.Select("DishID=" + DishList[i]["id"].ToString()).Count() > 0)
                {
                    DataRow row = DishList[i];
                    bool flag = true;
                    DataTable dt_info = new Catering_Rules.T_DishInfo().GetList(" DID=" + row["id"].ToString() + " ").Tables[0];
                    //验证配送区域
                    if (md_class.id != 50 && dt_info != null)
                    {
                        foreach (DataRow item0 in dt_info.Rows)
                        {
                            string RawID = item0["RawID"].ToString();
                            string checkwhere = " RAWID=" + RawID + " AND InDBID LIKE '" + md_class.AID + "%'";
                            DataTable dt_ck = new Catering_Rules.RawMaterial_Area().GetList(checkwhere).Tables[0];
                            if (dt_ck.Rows.Count == 0)
                            {
                                flag = false;
                                break;
                            }
                        }
                        dt_info.Dispose();
                    }
                    if (flag)
                    {
                        E_DishInfoEntity eDishInfo = new E_DishInfoEntity();
                        eDishInfo.id = Convert.ToInt32(DishList[i]["id"].ToString());
                        eDishInfo.Name = DishList[i]["Name"].ToString();
                        EDishList.Add(eDishInfo);
                        //string Temp = GetLoopContent(DishList[i], DishTemp);
                        //DishHtml.Append(Temp);
                    }
                }
            }
            return DishHtml.ToString();
        }

        //通过关键字查询符合要求的类别ID
        [WebMethod]
        public static ArrayList SearchDishByKeyWord(string Lid, string keyWord)
        {
            ArrayList al = new ArrayList();
            DataTable DishTypeDt = new Catering_Rules.library_Dish().GetDishTypeBykeyWord(int.Parse(Lid),keyWord).Tables[0]; //符合要求的类别
            al.Add("OK");
            string TypeIDS = "";
            for (int i = 0; i < DishTypeDt.Rows.Count; i++)
            {
                TypeIDS += DishTypeDt.Rows[i]["DTID"].ToString() + ",";
            }
            if (TypeIDS.Length > 0)
            {
                TypeIDS = TypeIDS.TrimEnd(',');
            }
            al.Add(TypeIDS);
            return al;
        }

        /// <summary>
        /// 获取已经处理过的LoopContent标签内容
        /// </summary>
        /// <param name="dt">数据源(DataTable)</param>
        /// <param name="LoopTempate">模版内容</param>
        /// <returns></returns>
        public static string GetLoopContent(DataRow row, string LoopTempate)
        {
            LoopTempate = LoopTempate.Replace("{$", "{");
            StringBuilder LoopContent = new StringBuilder();
            Regex Re = new Regex(@"{(.[^{}]+)}");
            MatchCollection Mats = Re.Matches(LoopTempate);
            StringBuilder LoopItem = new StringBuilder(LoopTempate);
            foreach (Match Mat in Mats)
            {
                LoopItem.Replace(Mat.Value, row[Re.Replace(Mat.Value, "$1")].ToString());
            }
            LoopContent.Append(LoopItem.ToString());
            LoopItem = null; Re = null; Mats = null;
            return LoopContent.ToString();
        }

        //元素列表
        [WebMethod]
        public static string GetNElements()
        {
            StringBuilder result = new StringBuilder("");
            DataTable dt = new Catering_Rules.NutritionElements().GetAllList().Tables[0];
            result.Append("{\"ElementInfo\":[");
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string ID = dt.Rows[i]["id"].ToString();
                    string Elements = dt.Rows[i]["Elements"].ToString();
                    string Company = dt.Rows[i]["Company"].ToString();
                    result.Append("{\"id\":\"" + ID + "\",\"Elements\":\"" + Elements + "\",\"Company\":\"" + Company + "\"}");
                    if (i < (dt.Rows.Count - 1)) result.Append(",");
                }
                dt.Dispose();
            }
            result.Append("]}");
            return result.ToString();
        }

        [WebMethod]
        public static ArrayList CaiPin_Info_Tedian(string Dish_ID)
        {
            ArrayList list = new ArrayList();
            Catering_Model.E_Dish md_Dish = new Catering_Rules.T_Dish().GetModel(Convert.ToInt32(Dish_ID));
            list.Add(md_Dish.Name);

            DataTable dt_DishInfo = new Catering_Rules.T_DishInfo().GetList("DID=" + Dish_ID).Tables[0];
            decimal reliang = 0;
            decimal danbaizhi = 0;
            decimal zhifang = 0;
            foreach (DataRow row in dt_DishInfo.Rows)
            {
                DataTable dt_NC = new Catering_Rules.NutrientComposition().GetList(24, "RawID=" + row["RawID"], "NutritionElementsID").Tables[0];
                reliang += Convert.ToDecimal(dt_NC.Select("NutritionElementsID=1")[0]["Content"].ToString().SetToString()) / 100 * Convert.ToDecimal(row["Content"].ToString());
                danbaizhi += Convert.ToDecimal(dt_NC.Select("NutritionElementsID=2")[0]["Content"].ToString().SetToString()) / 100 * Convert.ToDecimal(row["Content"].ToString());
                zhifang += Convert.ToDecimal(dt_NC.Select("NutritionElementsID=3")[0]["Content"].ToString().SetToString()) / 100 * Convert.ToDecimal(row["Content"].ToString());
            }
            list.Add(decimal.Round(reliang, 2).ToString());
            list.Add(decimal.Round(danbaizhi, 2).ToString());
            list.Add(decimal.Round(zhifang, 2).ToString());
            list.Add(md_Dish.Characteristic == null ? "无" : md_Dish.Characteristic);//特点
            return list;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="DishID">菜ID</param>
        /// <param name="FMID">餐别ID</param>
        /// <param name="DayOfWeek">第几天</param>
        /// <param name="WeekNoID">第几周ID</param>
        /// <param name="RecipesID">食谱ID</param>
        /// <returns></returns>
        [WebMethod]
        public static string AddDish(string DishID, string FMID, string DayOfWeek, string WeekNoID, string RecipesID)
        {
            StringBuilder result = new StringBuilder("");
            int wnid = 0, dish = 0, fm = 0, dayofw = 0, recpid = 0;
            Int32.TryParse(DishID, out dish);
            Int32.TryParse(FMID, out fm);
            Int32.TryParse(DayOfWeek, out dayofw);
            Int32.TryParse(WeekNoID, out wnid);
            Int32.TryParse(RecipesID, out recpid);
            Catering_Model.E_Recipes md_r = new Catering_Rules.T_Recipes().GetModel(recpid);
            //检查原料的配送区域
            Catering_Model.ClassInfo md_class = new Catering_Rules.ClassInfo().GetModel(md_r.ClassID);
            if (md_class.AID <= 0 && md_class.id != 50) return "NOCLASS";

            Catering_Model.E_RecipeInformation md = new Catering_Model.E_RecipeInformation();
            Catering_Model.E_RecipesWeek md_rw = new Catering_Rules.T_RecipesWeek().GetModel(wnid);
            if (md_rw != null) md.Date = md_rw.startDate.AddDays(((dayofw == 0 ? 7 : dayofw) - 1));
            //md.id = new Catering_Rules.RecipeInformation().GetMaxId();
            md.CID = dish;
            md.FMID = fm;
            md.MID = recpid;
            md.Week = dayofw;
            md.temp1 = md_rw.Number.ToString();
            new Catering_Rules.T_RecipeInformation().Add(md);

            Catering_Model.E_Dish md_dish = new Catering_Rules.T_Dish().GetModel(dish);
            List<Catering_Model.E_DishInfo> md_dishinfo = new Catering_Rules.T_DishInfo().GetModelList(" DID=" + dish);
            Catering_Model.FoodMealType md_fmt = new Catering_Rules.FoodMealType().GetModel(fm);
            result.Append("{\"DishName\":\"" + md_dish.Name + "\",\"CID\":\"" + dish + "\",\"DTID\":\"" + md_dish.DTID + "\",\"RecipeInformationID\":\"" + md.id + "\",\"CanBie\":\"" + md_fmt.temp1 + "\",\"DishInfo\":[");
            int i = 0;
            decimal DishPice = 0;
            string StrSafe = "";
            foreach (Catering_Model.E_DishInfo item in md_dishinfo)
            {
                Catering_Model.E_RecipeInformationInfo md_info = new Catering_Model.E_RecipeInformationInfo();
                md_info.Number = Convert.ToDecimal(item.Content);
                md_info.RecipeInformationID = md.id;
                md_info.RawID = item.RawID;
                new Catering_Rules.T_RecipeInformationInfo().Add(md_info);
                result.Append("{\"RawName\":\"" + item.DName + "\",\"AID\":\"" + md_info.id + "\",\"Number\":\"" + md_info.Number + "\"}");
                if (i < (md_dishinfo.Count() - 1))
                {
                    result.Append(",");
                }
                i++;
                DataTable dt_in = new Catering_Rules.InDbInfo().GetList(1, 1, " ClassID=" + md_r.ClassID + " AND RAWID=" + item.RawID + " ORDER BY IntDate DESC ").Tables[0];
                //decimal price = new Catering_Rules.BalanceInfo().GetPriceByRawID(md_r.ClassIDs, item.RawID.ToString(), DateTime.Now);//原单位价格
                if (md_class.id != 50)
                {
                    string checkwhere = " RAWID=" + item.RawID + " AND InDBID LIKE '" + md_class.AID + "%'";
                    DataTable dt_ck = new Catering_Rules.RawMaterial_Area().GetList(checkwhere).Tables[0];
                    if (dt_ck.Rows.Count == 0)
                    {
                        new Catering_Rules.T_RecipeInformation().Delete(md.id);
                        new Catering_Rules.T_RecipeInformationInfo().DeleteListBywhere(" RecipeInformationID=" + md.id);
                        return "NOROW";
                    }
                }

                #region 价格

                if (dt_in != null && dt_in.Rows.Count > 0)
                {
                    try
                    {
                        decimal number = Convert.ToDecimal(dt_in.Rows[0]["Number"]);
                        decimal price = Convert.ToDecimal(dt_in.Rows[0]["Price"]);
                        decimal sumnum = Convert.ToDecimal(dt_in.Rows[0]["SumNumber"]);
                        DishPice += Toolss.GetMathResult((number * price) / sumnum * Convert.ToInt32(md_info.Number), 2, 3);
                    }
                    catch { }
                    dt_in.Dispose();
                }

                #endregion
            }
            result.Append("],\"DishPice\":\"" + DishPice + "\",\"StrSafe\":\"" + StrSafe + "\"}");
            return result.ToString();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="RecipeInformationID"></param>
        /// <returns></returns>
        [WebMethod]
        public static string DelDish(string RecipeInformationID)
        {
            int id = 0;
            Int32.TryParse(RecipeInformationID, out id);
            if (id > 0)
            {
                new Catering_Rules.T_RecipeInformation().Delete(id);
                new Catering_Rules.T_RecipeInformationInfo().DeleteListBywhere(" RecipeInformationID=" + id);
            }
            return "OK";
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="RecipeInformationInfoID"></param>
        /// <param name="Number"></param>
        /// <returns></returns>
        [WebMethod]
        public static string ModifyDish(string RecipeInformationInfoID, string Number)
        {
            int id = 0;
            Int32.TryParse(RecipeInformationInfoID, out id);
            if (id > 0)
            {
                Catering_Model.E_RecipeInformationInfo md = new Catering_Rules.T_RecipeInformationInfo().GetModel(id);
                if (md != null) md.Number = Convert.ToDecimal(Number);
                new Catering_Rules.T_RecipeInformationInfo().Update(md);
                return "OK";
            }
            return "NO";
        }

        /// <summary>
        /// 获取经济评价及安全提示和种属来源
        /// </summary>
        /// <param name="StrRecipesID"></param>
        /// <param name="StrStartDay"></param>
        /// <param name="StrDayOfWeek"></param>
        /// <returns></returns>
        [WebMethod]
        public static ArrayList GetRecipesPrice(string StrRecipesID, string StrWeekNoID, string StrDayOfWeek)
        {
            int recipesid = 0, weeknoid = 0, dayofweek = 1;
            Int32.TryParse(StrRecipesID, out recipesid);
            Int32.TryParse(StrWeekNoID, out weeknoid);
            Int32.TryParse(StrDayOfWeek, out dayofweek);// 星期几，0代表星期日
            ArrayList al = new ArrayList();
            if (weeknoid > 0 && recipesid > 0)
            {
                string where = string.Format(" [RecipesID]={0} AND [RecipesWeekID]={1} AND [dayofweek]={2} ", recipesid, weeknoid, dayofweek);
                DataTable dt = new Catering_Rules.T_RecipeInformation().GetViewList(where);
                if (dt != null && dt.Rows.Count > 0)
                {
                    al = GetStringRecipesPriceFromDt(dt, dayofweek);
                }
            }
            return al;
        }

        /// <summary>
        /// 标准摄入量
        /// </summary>
        /// <param name="RecipeInformationInfoID"></param>
        /// <param name="Number"></param>
        /// <returns></returns>
        [WebMethod]
        public static ArrayList GetSheruliang(string StrRecipesID, string StrWeekNoID, string StrDayOfWeek, string FMNO)
        {
            int id = 0;//食谱ID
            int number = 0;//餐别
            int weeknoid = 0;//周ID
            int dayofweek = 0;//第几天
            Int32.TryParse(StrRecipesID, out id);
            Int32.TryParse(FMNO, out number);
            Int32.TryParse(StrWeekNoID, out weeknoid);
            Int32.TryParse(StrDayOfWeek, out dayofweek);

            ArrayList al_sheruliang = new ArrayList();
            al_sheruliang.Add(GetBiaoZhunNutrition(id, number));//标准
            al_sheruliang.Add(GetNutritionElement(StrRecipesID, StrWeekNoID, "-1", FMNO));//每周
            al_sheruliang.Add(GetNutritionElement(StrRecipesID, StrWeekNoID, StrDayOfWeek, FMNO));//每天
            return al_sheruliang;
        }

        //加载对应食谱库
        [WebMethod]
        public static ArrayList Getlibrary(string RecipesID)
        {
            ArrayList al = new ArrayList();
            StringBuilder sb = new StringBuilder();
            DataTable dt_library = new DataTable();
            Catering_Model.E_Recipes md_Recipes = new Catering_Rules.T_Recipes().GetModel(Convert.ToInt32(RecipesID));
            if (md_Recipes.PID == 0)//群体配餐
            {
                int GroupID = md_Recipes.GroupID;//群体配餐ID
                //DataTable dt_CateringGroupInfo = new Catering_Rules.CateringGroupInfo().GetList(1, "GroupID=" + GroupID, "id").Tables[0];
                //int TedianID = Convert.ToInt32(dt_CateringGroupInfo.Rows[0]["Group_tedianID"].ToString());
                //dt_library = new Catering_Rules.library().GetList("temp1='" + TedianID.ToString() + "'").Tables[0];
                dt_library = new Catering_Rules.library().GetList("").Tables[0];
            }
            else
            {
                int PID = md_Recipes.PID;
                Catering_Model.PersonalService md_PS = new Catering_Rules.PersonalService().GetModel(PID);
                dt_library = new Catering_Rules.library().GetList("temp1='" + md_PS.temp2 + "'").Tables[0];
            }

            if (dt_library != null && dt_library.Rows.Count > 0)
            {
                al.Add("OK");
                int i = 1;
                string tempid = "";
                string templname = "";

                //DataRow[] t_r = dt_library.Select("LName='北方菜谱'");
                //if (t_r != null && t_r.Count() > 0)
                //{

                //}
                foreach (DataRow row in dt_library.Rows)
                {
                    sb.Append("<tr uid=\"" + row["id"].ToString() + "\" uname=\"" + row["LName"].ToString() + "\"><td>" + i + "</td>");
                    sb.Append("<td>" + row["LName"].ToString() + "</td>");
                    sb.Append("<td>" + row["Back"].ToString() + "</td></tr>");
                    if (row["LName"].ToString() == "推荐菜系")
                    {
                        tempid = row["id"].ToString();
                        templname = row["LName"].ToString();
                    }
                    i += 1;
                }
                al.Add(sb.ToString());
                if (tempid == "" || templname == "")
                {
                    al.Add(dt_library.Rows[0]["id"].ToString());
                    al.Add(dt_library.Rows[0]["LName"].ToString());
                }
                else
                {
                    al.Add(tempid);
                    al.Add(templname);
                }
            }
            else
            {
                al.Add("NO");
            }
            return al;
        }

        /// <summary>
        /// 获取自动生成食谱
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public static ArrayList GetAutoRecipesParameter()
        {
            ArrayList al = new ArrayList();
            DataTable dt_a = new Catering_Rules.AutoRecipe().GetView_AutoRecipeList().Tables[0];

            if (dt_a != null && dt_a.Rows.Count > 0)
            {
                var d = from t in dt_a.AsEnumerable()
                        group t by new { t1 = t.Field<int>("FoodID") } into m
                        select new { FoodID = m.Key.t1 };
                d.ToList().OrderBy(o => o.FoodID).ToList().ForEach(o =>
                {
                    var fid = o.FoodID;
                    var m = from t in dt_a.AsEnumerable()
                            where t.Field<int>("FoodID") == fid
                            select new
                            {
                                ID = t.Field<int>("ID"),
                                TypeID = t.Field<int>("TypeID"),
                                TypeInfoID = t.Field<int>("TypeInfoID"),
                                Number = t.Field<int>("Number"),
                                FMName = t.Field<string>("FMName"),
                                DT = t.Field<string>("DT"),
                                DTName = t.Field<string>("DTName")
                            };
                    StringBuilder result = new StringBuilder("");
                    result.Append("<dl class='foodrecipe'>");
                    m.ToList().ForEach(p =>
                    {
                        string TypeName = p.DTName;
                        Catering_Model.DishType md = new Catering_Rules.DishType().GetModel(p.TypeInfoID);
                        if (md.ParentID != 0)
                        {
                            GetDishParentTypeName(md.ParentID, ref TypeName);
                        }
                        result.Append("<dd>" + TypeName + "：<input type='text' style='width:30px;' value='" + p.Number + "' autor='" + p.TypeInfoID + "'  /></dd>");
                    });
                    result.Append("</dl>");
                    al.Add(result.ToString());
                });
            }
            dt_a.Dispose();
            return al;
        }

        /// <summary>
        /// 获取父级菜品分类名称
        /// </summary>
        /// <param name="ParentID">父ID</param>
        /// <param name="TypeName">菜品分类名称</param>
        /// <returns>返回最终的菜品分类结构</returns>
        public static string GetDishParentTypeName(int ParentID, ref string TypeName)
        {
            Catering_Model.DishType md = new Catering_Rules.DishType().GetModel(ParentID);
            TypeName = md.DT + "-" + TypeName;
            if (md.ParentID != 0)
            {
                GetDishParentTypeName(md.ParentID, ref TypeName);
            }
            return TypeName;
        }


        //自动生成食谱
        [WebMethod]
        public static ArrayList SaveAutoRecipesParameter(string StrRecipesID, string StrWeekNoID, string breakfast, string lunch, string dinner)
        {
            ArrayList al = new ArrayList();
            int recipeid = 0;
            int weeknoid = 0;
            Int32.TryParse(StrRecipesID, out recipeid);
            Int32.TryParse(StrWeekNoID, out weeknoid);
            if (recipeid <= 0 || weeknoid <= 0)
            {
                al.Add("NO");
                return al;
            }
            Catering_Model.E_Recipes rep = new Catering_Rules.T_Recipes().GetModel(recipeid);
            Catering_Model.ClassInfo md_class = new Catering_Rules.ClassInfo().GetModel(rep.ClassIDs);
            if (md_class.AID <= 0 && md_class.id != 50)
            {
                al.Add("NO");
                return al;
            }

            #region 删除原有菜品

            DataTable dt_RecipeInformation = new Catering_Rules.T_RecipeInformation().GetList("MID=" + recipeid + " and Week=" + weeknoid).Tables[0];
            foreach (DataRow row in dt_RecipeInformation.Rows)
            {
                new Catering_Rules.T_RecipeInformationInfo().DeleteListBywhere("RecipeInformationID=" + row["id"].ToString());
            }
            new Catering_Rules.T_RecipeInformation().DeleteList("MID=" + recipeid + " and Week=" + weeknoid);

            #endregion

            List<int> dishui = new List<int>();

            Catering_Model.E_RecipesWeek rw = new Catering_Rules.T_RecipesWeek().GetModel(weeknoid);
            DataTable dt = new Catering_Rules.T_DishInfo().GetView_DishInfoList("").Tables[0];
            for (int dateno = 1; dateno <= (rw.endDate - rw.startDate).Days + 1; dateno++)
            {
                if (rw != null)
                {
                    AddFmDishAuto(dt, md_class.AID, md_class.id, breakfast, 1, recipeid, dishui, rw, dateno);
                    AddFmDishAuto(dt, md_class.AID, md_class.id, lunch, 2, recipeid, dishui, rw, dateno);
                    AddFmDishAuto(dt, md_class.AID, md_class.id, dinner, 3, recipeid, dishui, rw, dateno);
                }
            }
            dt.Dispose();
            al.Add("OK");
            return al;
        }

        private static void AddFmDishAuto(DataTable dt, int AID, int classid, string breakfast, int fmid, int recipeid, List<int> dishui, Catering_Model.E_RecipesWeek rw, int dateno)
        {
            string[] zsui = breakfast.Split('|');
            if (zsui.Length > 1)
            {
                for (int i = 0; i < zsui.Length; i++)
                {
                    if (string.IsNullOrEmpty(zsui[i])) continue;
                    string[] zs = zsui[i].Split(',');
                    if (zs.Length == 2)
                    {
                        int dtsid = 0;//dishtypesid
                        int dtsno = 0;//数量
                        Int32.TryParse(zs[0], out dtsid);
                        Int32.TryParse(zs[1], out dtsno);
                        AddDishByAuto(dt, AID, classid, recipeid, dishui, rw, dateno, dtsid, dtsno, fmid);
                    }
                }
            }
        }

        /// <summary>
        /// 添加自动生成食谱
        /// </summary>
        /// <param name="recipeid"></param>
        /// <param name="dishui"></param>
        /// <param name="rw"></param>
        /// <param name="dateno"></param>
        /// <param name="dtsid"></param>
        /// <param name="dtsno"></param>
        private static void AddDishByAuto(DataTable dt, int AID, int classid, int recipeid, List<int> dishui, Catering_Model.E_RecipesWeek rw, int dateno, int dtsid, int dtsno, int fmid)
        {
            string whereclause = " DishTypesID=" + dtsid;

            DataRow[] dtui = dt.Select(whereclause);
            Catering_Model.RecipesRule rr = new Catering_Rules.RecipesRule().GetModel(recipeid, dtsid);
            int checkruletype = 0;  //菜品分类
            int checkruleno = 0;    //重复数量
            if (rr != null)//判断重复项添加
            {
                checkruletype = rr.Repeatype;
                checkruleno = rr.RepeatNo + 1;
            }
            else
            {
                Catering_Model.RecipesRuleManage rrm = new Catering_Rules.RecipesRuleManage().GetModel(dtsid);
                checkruletype = rrm.Repeatype;
                checkruleno = rrm.DefaultNo + 1;
            }
            if (dtui != null && dtui.Count() > 0)
            {
                for (int t = 0; t < dtsno; t++)
                {
                    int id = 0;
                    bool flag = false;//是否执行do循环
                    bool flagfor = true;//是否执行for循环
                    int donum = 0;
                    do
                    {
                        Random rd = new Random();
                        int index = rd.Next(0, dtui.Length - 1);//rd.Next(0, dt.Rows.Count - 1);
                        id = Convert.ToInt32(dtui[index]["ID"]); //Convert.ToInt32(dt.Rows[index]["ID"]);

                        if (dishui.Contains(id))//菜品已经添加过
                        {
                            string search = " AND MID=" + recipeid + " AND CID=" + id + " AND FMID=" + fmid + " AND Date='" + rw.startDate.AddDays((dateno - 1)).ToString("yyyy-MM-dd") + "' ";
                            int rowcount = new Catering_Rules.T_RecipeInformation().GetCount(search);
                            if (rowcount > 0)//判断每餐是否重复
                            {
                                flag = true;
                            }
                            else if (checkruletype == 1)//每天可重复
                            {
                                search = " AND MID=" + recipeid + " AND CID=" + id + " AND Date='" + rw.startDate.AddDays((dateno - 1)).ToString("yyyy-MM-dd") + "' ";
                                rowcount = new Catering_Rules.T_RecipeInformation().GetCount(search);
                                if (rowcount > checkruleno) flag = true;//此菜品以重复，添加别的菜品
                            }
                            else//每周可重复
                            {
                                search = " AND MID=" + recipeid + " AND CID=" + id + " AND temp1='" + rw.Number + "' ";
                                rowcount = new Catering_Rules.T_RecipeInformation().GetCount(search);
                                if (rowcount > checkruleno) flag = true;//此菜品以重复，添加别的菜品
                            }
                        }

                        ////检查原料的配送区域
                        if (!flag && classid != 50)
                        {
                            var a = from t1 in dt.AsEnumerable()
                                    where t1.Field<Int32>("ID") == id
                                    select new
                                    {
                                        RawID = t1.Field<Int32>("RawID"),
                                        Content = t1.Field<string>("Content")
                                    };
                            a.ToList().ForEach(o =>
                            {
                                string checkwhere = " RAWID=" + o.RawID + " AND InDBID LIKE '" + AID + "%'";
                                DataTable dt_ck = new Catering_Rules.RawMaterial_Area().GetList(checkwhere).Tables[0];
                                if (dt_ck.Rows.Count == 0) flag = true;
                            });
                        }
                        donum++;
                        if (donum > 40 && flag == true)
                        {
                            flag = false;
                            flagfor = false;
                        }
                    }
                    while (flag);
                    if (!flagfor) continue;
                    Catering_Model.E_RecipeInformation rif = new Catering_Model.E_RecipeInformation();
                    //rif.id = new Catering_Rules.T_RecipeInformation().GetMaxId();
                    rif.MID = recipeid;
                    rif.FMID = fmid;
                    rif.Date = rw.startDate.AddDays((dateno - 1));
                    rif.CID = id;
                    rif.Week = dateno == 7 ? 0 : dateno;
                    rif.Price = 0;
                    rif.temp1 = rw.Number.ToString();
                    new Catering_Rules.T_RecipeInformation().Add(rif);
                    var d = from t1 in dt.AsEnumerable()
                            where t1.Field<Int32>("ID") == id
                            select new
                            {
                                RawID = t1.Field<Int32>("RawID"),
                                Content = t1.Field<string>("Content"),
                                ZhShuID = t1.Field<Int32>("ZhShuID"),
                            };
                    d.ToList().ForEach(o =>
                    {
                        Catering_Model.E_RecipeInformationInfo rii = new Catering_Model.E_RecipeInformationInfo();
                        rii.RawID = o.RawID;
                        rii.Number = Convert.ToDecimal(o.Content);
                        rii.RecipeInformationID = rif.id;
                        new Catering_Rules.T_RecipeInformationInfo().Add(rii);
                    });
                    dishui.Add(id);
                }
            }
        }

        /// <summary>
        /// 智能分配菜品用量
        /// </summary>
        /// <param name="StrRecipesID"></param>
        /// <param name="StrWeekNoID"></param>
        /// <param name="StrDayOfWeek"></param>
        /// <param name="StrQinRow"></param>
        /// <param name="StrYuXia"></param>
        /// <param name="StrShCai"></param>
        /// <returns></returns>
        [WebMethod]
        public static string AutoUpdateDishNumber(string StrRecipesID, string StrWeekNoID, string StrDayOfWeek, string StrQinRow, string StrYuXia, string StrShCai)
        {
            StringBuilder result = new StringBuilder("{\"UpdateInfo\":[");
            //禽肉每日标准量：50-75g,[RAWZS]=3
            //鱼虾每日标准量：50-100g,[RAWZS]=4
            //蔬菜每日标准量：300-500g,[RAWZS]=4
            int recipesid = 0, weeknoid = 0, dayofweek = 0;
            decimal qinrow = 0, yuxia = 0, shcai = 0;
            Int32.TryParse(StrRecipesID, out recipesid);
            Int32.TryParse(StrWeekNoID, out weeknoid);
            Int32.TryParse(StrDayOfWeek, out dayofweek);
            Decimal.TryParse(StrQinRow, out qinrow);
            Decimal.TryParse(StrYuXia, out yuxia);
            Decimal.TryParse(StrShCai, out shcai);

            decimal q_yueshu = qinrow / (50 + 75) * 2;//禽肉类超量
            decimal y_yueshu = yuxia / (50 + 100) * 2;//鱼虾类超量
            decimal s_yueshu = shcai / (300 + 500) * 2;//蔬菜类超量

            string where = string.Format(" [RecipesID]={0} AND [RecipesWeekID]={1} AND [dayofweek]={2} AND DishName NOT LIKE 'N%' ", recipesid, weeknoid, dayofweek);
            //获取当天所有禽肉类菜品
            DataTable dt_q = new Catering_Rules.T_RecipeInformation().GetViewList(where + " AND [RAWZS]=3 ");
            if (dt_q != null && dt_q.Rows.Count > 0)
            {
                for (int i = 0; i < dt_q.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt_q.Rows[i]["AID"]);
                    decimal number = Convert.ToDecimal(dt_q.Rows[i]["Number"]);
                    Catering_Model.E_RecipeInformationInfo ri = new Catering_Rules.T_RecipeInformationInfo().GetModel(id);
                    ri.Number = Toolss.GetMathResult(number / q_yueshu, 0, 2);
                    new Catering_Rules.T_RecipeInformationInfo().Update(ri);
                    result.Append("{\"ID\":\"" + id + "\",\"Number\":\"" + ri.Number + "\"},");
                }
                dt_q.Dispose();
            }

            //获取当天所有鱼虾类菜品
            dt_q = new Catering_Rules.T_RecipeInformation().GetViewList(where + " AND [RAWZS]=4 ");
            if (dt_q != null && dt_q.Rows.Count > 0)
            {
                for (int i = 0; i < dt_q.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt_q.Rows[i]["AID"]);
                    decimal number = Convert.ToDecimal(dt_q.Rows[i]["Number"]);
                    Catering_Model.E_RecipeInformationInfo ri = new Catering_Rules.T_RecipeInformationInfo().GetModel(id);
                    ri.Number = Toolss.GetMathResult(number / y_yueshu, 0, 2);
                    new Catering_Rules.T_RecipeInformationInfo().Update(ri);
                    result.Append("{\"ID\":\"" + id + "\",\"Number\":\"" + ri.Number + "\"},");
                }
                dt_q.Dispose();
            }

            //获取当天所有蔬菜类菜品
            dt_q = new Catering_Rules.T_RecipeInformation().GetViewList(where + " AND [RAWZS]=6 ");
            if (dt_q != null && dt_q.Rows.Count > 0)
            {
                for (int i = 0; i < dt_q.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt_q.Rows[i]["AID"]);
                    decimal number = Convert.ToDecimal(dt_q.Rows[i]["Number"]);
                    Catering_Model.E_RecipeInformationInfo ri = new Catering_Rules.T_RecipeInformationInfo().GetModel(id);
                    ri.Number = Toolss.GetMathResult(number / s_yueshu, 0, 2);
                    new Catering_Rules.T_RecipeInformationInfo().Update(ri);
                    result.Append("{\"ID\":\"" + id + "\",\"Number\":\"" + ri.Number + "\"},");
                }
                dt_q.Dispose();
            }
            result.Append("{\"ID\":\"0\",\"Number\":\"0\"}");
            result.Append("]}");
            return result.ToString();
        }

        /// <summary>
        /// 获取标准摄入量
        /// </summary>
        /// <param name="id">食谱ID</param>
        /// <param name="number">餐别ID</param>
        /// <returns></returns>
        private static decimal[] GetBiaoZhunNutrition(int id, int number)
        {
            decimal[] list = new decimal[24];
            decimal[] bl_Num = new decimal[24]; //存放最后的标量值
            StringBuilder sb = new StringBuilder();//标量值查询条件
            sb.Append("1=2");
            if (id > 0)
            {
                Catering_Model.E_Recipes md_shipu = new Catering_Rules.T_Recipes().GetModel(id);
                if (md_shipu != null && md_shipu.GroupID > 0)
                {
                    DataTable dt = new Catering_Rules.CateringGroupInfo().GetNETypes(md_shipu.GroupID).Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            string Group_tedianId = row["Group_tedianID"].ToString(); //适合人群
                            string SexId = row["SexID"].ToString();//性别
                            string AgeId = row["OldAreaID"].ToString();//年龄段
                            string LaborGradeId = row["LaborGradeID"].ToString();//劳动级别
                            string strwhere = "SexID=" + SexId + " and OldAreaID=" + AgeId + " and LaborGradeID=" + LaborGradeId + " and Group_tedianID=" + Group_tedianId;
                            sb.Append(" or (" + strwhere + ")");
                        }
                        dt.Dispose();
                        //计算标量值
                        DataTable dt_Ingestion = new Catering_Rules.Ingestion().GetList(sb.ToString()).Tables[0];
                        foreach (DataRow row in dt_Ingestion.Rows)
                        {
                            bl_Num[Convert.ToInt32(row["NutritionElementsID"]) - 1] += Convert.ToDecimal(row["Number"]);
                        }
                        dt_Ingestion.Dispose();

                        for (int i = 0; i < 24; i++)
                        {
                            decimal tnum = Convert.ToDecimal(bl_Num[i]) / dt.Rows.Count;

                            if (number == 1 || number == 3)
                            {
                                tnum = (tnum / 10 * 3);
                            }
                            else if (number != 0)
                            {
                                tnum = (tnum / 10 * 4);
                            }
                            list[i] = Toolss.GetMathResult(tnum, 2, 3);
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取营养素实际值
        /// </summary>
        /// <param name="StrRecipesID"></param>
        /// <param name="StrWeekNoID"></param>
        /// <param name="StrDayOfWeek"></param>
        /// <param name="StrFMID"></param>
        /// <returns></returns>
        public static decimal[] GetNutritionElement(string StrRecipesID, string StrWeekNoID, string StrDayOfWeek, string StrFMID)
        {
            int recipesid = 0, weeknoid = 0, dayofweek = 1, fmid = 0;
            Int32.TryParse(StrRecipesID, out recipesid);
            Int32.TryParse(StrWeekNoID, out weeknoid);
            Int32.TryParse(StrDayOfWeek, out dayofweek);// 星期几，0代表星期日
            Int32.TryParse(StrFMID, out fmid);
            decimal[] r = new decimal[24];
            string where = string.Format(" AND b.[RecipesID]={0} AND b.[RecipesWeekID]={1} ", recipesid, weeknoid);
            if (dayofweek >= 0) where += string.Format("  AND b.[dayofweek]={0} ", dayofweek);
            switch (fmid)
            {
                case 1:
                    where += " AND b.FMID=1 ";
                    break;
                case 2:
                    where += " AND (b.FMID=2 OR b.FMID=5) ";
                    break;
                case 3:
                    where += " AND (b.FMID=3 OR b.FMID=6) ";
                    break;
                case 4:
                    where += " AND b.FMID=4 ";
                    break;
            }
            DataTable dt = new Catering_Rules.NutrientComposition().GetNutritionElementsNumber(where).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt.Rows[i]["NutritionElementsID"]);
                    decimal Number = Convert.ToDecimal(dt.Rows[i]["Number"]);
                    r[(id - 1)] = Number;
                }
                dt.Dispose();
            }
            return r;
        }



        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="OptionName"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public int GetInt(string OptionName, int DefaultValue)
        {
            if (Request.QueryString[OptionName] == null) return DefaultValue;
            string tempstr = Request.QueryString[OptionName].ToString();
            Int32.TryParse(tempstr, out DefaultValue);
            return DefaultValue;
        }



        /// <summary>  
        /// 将DataTable转换为JSON字符串  
        /// </summary>  
        /// <param name="dt">数据表</param>  
        /// <returns>JSON字符串</returns>  
        public static string GetJsonFromDataTable(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"TableInfo\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 将DataTable转换为JSON字符串 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetJsonFromViewRecipes(DataTable dt)
        {
            var d = from t in dt.AsEnumerable()
                    select new
                    {
                        RecipesID = t.Field<int>("RecipesID"),
                        RecipesWeekID = t.Field<int>("RecipesWeekID"),
                        dayofweek = t.Field<int>("dayofweek"),
                        FMID = t.Field<int>("FMID"),
                        CanBie = t.Field<string>("CanBie"),
                        CID = t.Field<int>("CID"),
                        DishName = t.Field<string>("DishName"),
                        Date = t.Field<DateTime>("Date"),
                        WeekNo = t.Field<int>("WeekNo"),
                        DTID = t.Field<int>("DTID"),
                        RecipeInformationID = t.Field<int>("RecipeInformationID"),

                        AID = t.Field<int>("AID"),
                        RawID = t.Field<int>("RawID"),
                        Number = t.Field<decimal>("Number"),
                        RAWName = t.Field<string>("RAWName")
                    };
            var a = from t in d
                    group t by new
                    {
                        t1 = t.RecipesID,
                        t2 = t.RecipesWeekID,
                        t3 = t.dayofweek,
                        t4 = t.FMID,
                        t5 = t.CID,
                        t6 = t.CanBie,
                        t7 = t.RecipeInformationID
                    } into m
                    select new
                    {
                        RecipesID = m.Key.t1,
                        RecipesWeekID = m.Key.t2,
                        dayofweek = m.Key.t3,
                        FMID = m.Key.t4,
                        CID = m.Key.t5,
                        CanBie = m.Key.t6,
                        RecipeInformationID = m.Key.t7,
                        DishName = m.First().DishName,
                        Date = m.First().Date,
                        WeekNo = m.First().WeekNo,
                        DTID = m.First().DTID
                    };

            StringBuilder JsonString = new StringBuilder();
            JsonString.Append("{ ");
            JsonString.Append("\"TableInfo\":[ ");
            int i = 0;
            a.ToList().ForEach(o =>
            {
                JsonString.Append("{ ");
                // JsonString.Append("\"RecipesID\":" + "\"" + o.RecipesID + "\",");
                // JsonString.Append("\"RecipesWeekID\":" + "\"" + o.RecipesWeekID + "\",");
                //JsonString.Append("\"dayofweek\":" + "\"" + o.dayofweek + "\",");
                // JsonString.Append("\"FMID\":" + "\"" + o.FMID + "\",");
                JsonString.Append("\"CanBie\":" + "\"" + o.CanBie + "\",");
                JsonString.Append("\"CID\":" + "\"" + o.CID + "\",");
                JsonString.Append("\"DishName\":" + "\"" + o.DishName + "\",");
                //JsonString.Append("\"Date\":" + "\"" + o.Date + "\",");
                //JsonString.Append("\"WeekNo\":" + "\"" + o.WeekNo + "\",");
                JsonString.Append("\"DTID\":" + "\"" + o.DTID + "\",");
                JsonString.Append("\"RecipeInformationID\":" + "\"" + o.RecipeInformationID + "\",");
                var k = d.ToList().Where(t => (t.RecipesID == o.RecipesID) && (t.RecipesWeekID == o.RecipesWeekID) && (t.dayofweek == o.dayofweek) && (t.FMID == o.FMID) && (t.CID == o.CID) && (t.RecipeInformationID == o.RecipeInformationID));
                JsonString.Append("\"DisInfo\":[ ");
                int j = 0;
                k.ToList().ForEach(m =>
                {
                    JsonString.Append("{ ");
                    JsonString.Append("\"AID\":" + "\"" + m.AID + "\",");
                    JsonString.Append("\"RawID\":" + "\"" + m.RawID + "\",");
                    JsonString.Append("\"Number\":" + "\"" + m.Number.ToString().TrimEnd('0').TrimEnd('0').TrimEnd('.') + "\",");
                    JsonString.Append("\"RAWName\":" + "\"" + m.RAWName + "\"");
                    if (j == (k.Count() - 1))
                    {
                        JsonString.Append("}");
                    }
                    else
                    {
                        JsonString.Append("},");
                    }
                    j++;
                });
                JsonString.Append("]");
                if (i == (a.ToList().Count() - 1))
                {
                    JsonString.Append("}");
                }
                else
                {
                    JsonString.Append("},");
                }
                i++;
            });
            JsonString.Append("]}");
            return JsonString.ToString();
        }

        /// <summary>
        /// 获取经济评价及食谱安全提示html
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dayofweek">周几，0：周日</param>
        /// <returns></returns>
        public static ArrayList GetStringRecipesPriceFromDt(DataTable dt, int dayofweek)
        {
            dayofweek = dayofweek == 0 ? 7 : dayofweek;
            ArrayList al = new ArrayList();
            var d = from t in dt.AsEnumerable()
                    select new
                    {
                        RecipesID = t.Field<int>("RecipesID"),
                        RecipesWeekID = t.Field<int>("RecipesWeekID"),
                        dayofweek = t.Field<int>("dayofweek"),
                        FMID = t.Field<int>("FMID"),
                        CanBie = t.Field<string>("CanBie"),
                        CID = t.Field<int>("CID"),
                        DishName = t.Field<string>("DishName"),
                        Date = t.Field<DateTime>("Date"),
                        WeekNo = t.Field<int>("WeekNo"),
                        //DTID = t.Field<int>("DTID"),
                        RecipeInformationID = t.Field<int>("RecipeInformationID"),

                        AID = t.Field<int>("AID"),
                        RawID = t.Field<int>("RawID"),
                        Number = t.Field<decimal>("Number"),
                        RAWName = t.Field<string>("RAWName")
                    };
            var a = from t in d
                    group t by new
                    {
                        t1 = t.RecipesID,
                        t2 = t.RecipesWeekID,
                        t3 = t.dayofweek,
                        t4 = t.FMID,
                        t5 = t.CID,
                        t6 = t.CanBie,
                        t7 = t.RecipeInformationID
                    } into m
                    select new
                    {
                        RecipesID = m.Key.t1,
                        RecipesWeekID = m.Key.t2,
                        dayofweek = m.Key.t3,
                        FMID = m.Key.t4,
                        CID = m.Key.t5,
                        CanBie = m.Key.t6,
                        RecipeInformationID = m.Key.t7,
                        DishName = m.First().DishName,
                        Date = m.First().Date,
                        WeekNo = m.First().WeekNo,
                        //DTID = m.First().DTID
                    };
            StringBuilder result = new StringBuilder();
            decimal TotalPrice = 0;
            string StrSafe = "";
            Dictionary<int, decimal> dic = new Dictionary<int, decimal>();
            a.ToList().ForEach(o =>
            {
                var k = d.ToList().Where(t => (t.RecipesID == o.RecipesID) && (t.RecipesWeekID == o.RecipesWeekID) && (t.dayofweek == o.dayofweek) && (t.FMID == o.FMID) && (t.CID == o.CID) && (t.RecipeInformationID == o.RecipeInformationID));
                decimal DishPice = 0;
                k.ToList().ForEach(m =>
                {
                    Catering_Model.E_Recipes md_Recipes = new Catering_Rules.T_Recipes().GetModel(m.RecipesID);
                    int PID_ClassID = md_Recipes.ClassIDs;
                    if (md_Recipes.PID != 0) PID_ClassID = Convert.ToInt32(HttpContext.Current.Session["ClassID"].ToString());//个人配餐
                    DataTable dt_in = new Catering_Rules.InDbInfo().GetList(1, 1, " ClassID=" + PID_ClassID + " AND RAWID=" + m.RawID + " ORDER BY IntDate DESC ").Tables[0];
                    //decimal price = new Catering_Rules.BalanceInfo().GetPriceByRawID(PID_ClassID, m.RawID.ToString(), DateTime.Now);//原单位价格
                    Catering_Model.E_RawMaterial md_RawMaterial = new Catering_Rules.T_RawMaterial().GetModel(m.RawID);
                    if (md_RawMaterial != null)
                    {
                        //安全提示
                        if (md_RawMaterial.SafetyTips != null && !string.IsNullOrEmpty(md_RawMaterial.SafetyTips)) StrSafe += "<span sa_infoid='" + o.RecipeInformationID + "'>" + md_RawMaterial.RAWName + ":" + md_RawMaterial.SafetyTips + "；</span>";

                        #region 价格

                        if (dt_in != null && dt_in.Rows.Count > 0)
                        {
                            try
                            {
                                decimal number = Convert.ToDecimal(dt_in.Rows[0]["Number"]);
                                decimal price = Convert.ToDecimal(dt_in.Rows[0]["Price"]);
                                decimal sumnum = Convert.ToDecimal(dt_in.Rows[0]["SumNumber"]);
                                DishPice += Toolss.GetMathResult((number * price) / sumnum * m.Number, 2, 3);
                            }
                            catch { }
                            dt_in.Dispose();
                        }

                        #endregion

                        if (dic.ContainsKey(md_RawMaterial.RAWZS))
                        {
                            dic[md_RawMaterial.RAWZS] += m.Number;
                        }
                        else
                        {
                            dic.Add(md_RawMaterial.RAWZS, m.Number);
                        }
                    }
                });
                result.Append("<span pr_infoid='" + o.RecipeInformationID + "' Number='" + DishPice + "'>" + o.DishName + ":" + DishPice + "，</span>");
                TotalPrice += DishPice;
            });
            al.Add("总价:<span id='totalprice_" + dayofweek + "'>" + TotalPrice + "</span>；" + result.ToString().TrimEnd('，'));
            al.Add(StrSafe);
            al.Add(dic.ToList());
            return al;
        }

        //通过食谱ID 获取周期
        public string GetZhouOptionByRid(string Rid)
        {
            DataTable dt_Week = new Catering_Rules.T_RecipesWeek().GetList("RecipesID=" + Rid.ToString() + " order by Number").Tables[0];
            StringBuilder sb = new StringBuilder();
            if (dt_Week != null && dt_Week.Rows.Count > 0)
            {
                foreach (DataRow row in dt_Week.Rows)
                {
                    string startTime = Convert.ToDateTime(row["startDate"].ToString()).ToShortDateString();
                    string endTime = Convert.ToDateTime(row["endDate"].ToString()).ToShortDateString();
                    sb.Append("<option value=\"" + startTime + "|" + endTime + "\" RecipesWeekID=\"" +row["id"].ToString()+ "\">" + row["temp1"].ToString() + "</option>");
                }
            }
            return sb.ToString();
        }


        /// <summary>
        /// 加载食谱库
        /// </summary>
        protected void LoadRep()
        {
            DataTable dt_RecipesByIsBiaoZhun = new DataTable();
            DataTable dt_RecipesByClass = new DataTable();

            dt_RecipesByIsBiaoZhun = new Catering_Rules.T_Recipes().GetList(
                    " (ClassID IN(SELECT ClassID FROM View_CompanyClass WHERE "
                    + " CompanyID=(SELECT TOP 1 CompanyID FROM View_CompanyClass WHERE ClassID="
                    + LoginPersonnel.ClassID + ")) AND IsBiaoZhun=1 )").Tables[0];
            if (LoginPersonnel.RoleName == "管理员")
            {
                dt_RecipesByClass = new Catering_Rules.T_Recipes().GetAllList().Tables[0];
            }
            else
            {
                if (LoginPersonnel.ClassID > 0)
                {
                    dt_RecipesByClass = new Catering_Rules.T_Recipes().GetList(" ClassID=" + LoginPersonnel.ClassID).Tables[0];
                }
            }
            this.Rep_shipuList.DataSource = dt_RecipesByIsBiaoZhun;
            this.Rep_shipuList.DataBind();

            this.Rep_shipuListByClass.DataSource = dt_RecipesByClass;
            this.Rep_shipuListByClass.DataBind();
        }

        //加载食谱
        protected void Recipes_List_Click(object sender, EventArgs e)
        {
            m_recipesid = Convert.ToInt32(this.hf_recipesid.Value);
            m_weekno = Convert.ToInt32(this.hf_weekNo.Value);
            m_shiwuzhongsh = GetShiWuZhongShu();
            LoadRecipesInfo();
        }

        [WebMethod]
        public static string SaveRecipesRepeatList(string recipes, string str)
        {
            int recipesid = 0;
            Int32.TryParse(recipes, out recipesid);
            if (recipesid == 0) return "NO";
            if (string.IsNullOrEmpty(str)) return "NO";
            string[] ui = str.Split('|');
            if (ui.Length == 0) return "NO";
            foreach (string i in ui)
            {
                if (string.IsNullOrEmpty(i)) continue;
                string[] op = i.Split(',');
                if (op.Length != 3) continue;
                int id = Convert.ToInt32(op[0]);
                int repeattype = Convert.ToInt32(op[1]);
                int no = Convert.ToInt32(op[2]);
                Catering_Model.RecipesRule rm = new Catering_Rules.RecipesRule().GetModel(recipesid, id);
                if (rm != null)
                {
                    rm.Repeatype = repeattype;
                    rm.RepeatNo = no;
                    new Catering_Rules.RecipesRule().Update(rm);
                }
                else
                {
                    rm = new Catering_Model.RecipesRule();
                    rm.RecipesID = recipesid;
                    rm.DTID = id;
                    rm.Repeatype = repeattype;
                    rm.RepeatNo = no;
                    new Catering_Rules.RecipesRule().Add(rm);
                }
            }
            return "OK";
        }

        //复制食谱
        //<param name="RecipesWeekID">要进行复制的食谱周期</param>
        //<param name="CopyRecipesWeekID">采用的食谱周期模版</param>
        [WebMethod]
        public static ArrayList CopyRecipes(string RecipesWeekID, string CopyRecipesWeekID)
        {
            T_RecipesWeek tRecipesWeek = new T_RecipesWeek();//食谱周期管理
            T_RecipeInformation tRecipeInformation = new T_RecipeInformation();//食谱菜品管理
            T_RecipeInformationInfo tRecipeInformationInfo = new T_RecipeInformationInfo();//食谱菜品用量详细管理

            ArrayList al = new ArrayList();
            E_RecipesWeek eRecipesWeek = tRecipesWeek.GetModel(int.Parse(RecipesWeekID));
            E_RecipesWeek eCopyRecipesWeek = tRecipesWeek.GetModel(int.Parse(CopyRecipesWeekID));

            //删除该食谱的本周菜品
            List<E_RecipeInformation> DelList = tRecipeInformation.GetModelList("MID=" + eRecipesWeek.RecipesID);
            string DelItemInfoIDS = "";
            foreach (E_RecipeInformation item in DelList)
            {
                DelItemInfoIDS += item.id+",";
            }
            if (DelItemInfoIDS.Length > 0)
            {
                DelItemInfoIDS = DelItemInfoIDS.TrimEnd(',');
                tRecipeInformationInfo.DeleteListBywhere("RecipeInformationID in (" + DelItemInfoIDS + ")");
                tRecipeInformation.DeleteListBywhere("MID=" + eRecipesWeek.RecipesID);
            }

            //循环遍历需要复制食谱周期
            int TempAddDays = 0; //用于周期日期对应的临时变量
            for (DateTime Temp = eCopyRecipesWeek.startDate; Temp <= eCopyRecipesWeek.endDate; Temp=Temp.AddDays(1))
            {
                DateTime Date=eRecipesWeek.startDate.AddDays(TempAddDays);
                if (Date <= eRecipesWeek.endDate)//判断当前日期是否符合要求
                { 
                    //获取需要复制的食谱菜品选择信息
                    string StrWhere = "MID=" + eCopyRecipesWeek.RecipesID + " and Date=cast('" + Temp + "' as datetime)";
                    List<E_RecipeInformation> CopyRecipeInformationList = tRecipeInformation.GetModelList(StrWhere);
                    foreach (E_RecipeInformation item in CopyRecipeInformationList)
                    {
                        int TempRecipeInformationID = item.id; //临时存储的ID
                        item.MID = int.Parse(eRecipesWeek.RecipesID.ToString()); //赋值为当前食谱的ID
                        item.Date = Date;//赋值为当前食谱对应的日期
                        item.IsExamine = null;
                        item.ExamineUserID = null;
                        item.ExamineUserName = null;
                        tRecipeInformation.Add(item);

                        //复制对应的菜品用量详细
                        List<E_RecipeInformationInfo> InfoList = tRecipeInformationInfo.GetModelList("RecipeInformationID=" + TempRecipeInformationID);
                        foreach (E_RecipeInformationInfo iteminfo in InfoList)
                        {
                            iteminfo.RecipeInformationID = item.id;
                            tRecipeInformationInfo.Add(iteminfo);
                        }
                    }
                }
                TempAddDays += 1;
            }
            al.Add("OK");
            return al;
        }

        //导出食谱Execl
        protected void Btn_ExportRecipes_Click(object sender, EventArgs e)
        {
            string HtmlTableJson = this.HidHtmlTableJson.Value;
            string ExeclFileName=Guid.NewGuid().ToString() + ".xls";
            HtmlTableExport.RenderToExcel(HtmlTableJson, Server.MapPath("~/ExportExecl/" + ExeclFileName));
            Response.Redirect("/ExportExecl/" + ExeclFileName);
        }
    }
}